// 引入qrcode.js库
// import QRCode from 'qrcodejs'

// import logoUrl from '@/assets/logo.png'

function getFontWidth(fonSize, fontFace, ctx, text) {
    ctx.font = fonSize + 'px ' + fontFace
    let txtWidth = 0
    for (let i = 0; i < text.length; i++) {
        txtWidth += ctx.measureText(text[i]).width
    }
    return txtWidth
}

export default (link,text,options,logoUrl)=> {
    return new Promise((resolve)=>{
        // 获取DOM元素
        const qrCodeContainer = document.createElement('div')
        var qrcode = new QRCode(qrCodeContainer, {
            text: link,
            width: options.width,
            height: options.width,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.H
        })
        // 在二维码上添加logo
        const logoImage = new Image()
        logoImage.src = logoUrl
        const width = options.width;
        const height = options.width;
        logoImage.onload = function() {
            const logoW = 50;
            const w = logoW
            const h = w / this.width * this.height
            const canvas = qrCodeContainer.getElementsByTagName("canvas")[0]
            console.log(canvas)
            const ctx = canvas.getContext('2d')
            ctx.drawImage(logoImage, (canvas.width - w) / 2, (canvas.height - h) / 2, w, h)
            const base64 = canvas.toDataURL('image/jpeg', 1)
            var canvas2 = document.createElement('canvas')
            canvas2.width = width
            canvas2.height = height
            const ctx2 = canvas2.getContext('2d')
            ctx2.fillStyle = '#ffffff'
            ctx2.fillRect(0, 0, width, height)
            const img = new Image()
            img.src = base64
            img.onload = function() {
                ctx2.drawImage(img, logoW/2, 0, options.width - logoW, options.width - logoW)
                const base642 = canvas.toDataURL('image/jpeg', 1)
                resolve(base642)
            }
        }
    })
}
